-- ChangeWallpaper.lua
-- Written by jusjoken
-- used to read a text file and randomly set the wallpaper to one of the files listed

function Initialize()
	
	MyDebug = SKIN:GetVariable('LuaDebug','0')
	if MyDebug=='1' then print('ChangeWallpaper: Init called') end

	-- Global variables to control if and when the weather backgrounds are changed for the Windows Wallpaper
	CWSwitchWallpaper = tonumber(SKIN:GetVariable('CWSwitchWallpaper'))
	CWSwitchWallpaperDelay = tonumber(SKIN:GetVariable('CWSwitchWallpaperDelay'))
	CWSwitchWallpaperMode = SKIN:GetVariable('CWSwitchWallpaperMode','Stretch')
	
	if CWSwitchWallpaperDelay==0 then CWSwitchWallpaperDelay = -1 end
	CWSwitchWallpaperDir = SKIN:GetVariable('CWSwitchWallpaperDir','#@#Images\\Gemstone\\Weather\\Backgrounds')
	CWSwitchWallpaperTemp = SKIN:GetVariable('CWSwitchWallpaperTemp','#@#Temp\\CWSwitchWallpaperTemp.txt')
	lastBG = nil
end

function Update()
	if MyDebug=='1' then print('ChangeWallpaper: Update called') end
	
	file = assert(io.open(CWSwitchWallpaperTemp, "r"))
	local line = file:read()
	local BGtable = {}
	for line in file:lines() do
		table.insert(BGtable,line)
	end
	file:close()
	
	local thisBG = BGtable[ math.random( #BGtable ) ]
	if thisBG==lastBG then
		--try one more time to get a different random BG
		thisBG = BGtable[ math.random( #BGtable ) ]
	end
	if thisBG~=lastBG then
		--change the wallpaper
		lastBG = thisBG
		CWCondCode = SKIN:GetVariable('CWCondCode','-1')
		if CWCondCode~='-1' then
			SKIN:Bang('!SetWallpaper',CWSwitchWallpaperDir..'\\'..CWCondCode..'\\'..thisBG , CWSwitchWallpaperMode)
			if MyDebug=='1' then print('BGPath: '..CWSwitchWallpaperDir..'\\'..CWCondCode..'\\'..thisBG) end
		else
			if MyDebug=='1' then print('ChangeWallpaper: invalid CWCondCode passed') end
		end
	end
	
end